<?php
namespace Common\Model;

use Think\Model;

class ConfigModel extends Model
{
    /**
     * 根据key找数据.
     */
    public function _find_by_key($key = '')
    {
        $map = ['key' => $key];
        $ret = $this->where($map)->find();
        if (!$ret) {
            $this->add(
                [
                    'key' => $key,
                    'config' => json_encode([], JSON_UNESCAPED_UNICODE),
                    'update_time' => time(),
                ]
            );
            $ret = $this->where($map)->find();
        }
        $ret['config'] = json_decode($ret['config'], true);

        return $ret;
    }

    /**
     * 列表数据,还没有全部写完，基础查询而已.
     */
    public function _query($p = 1, $row = 10, $query = '')
    {
        $sql = 'SELECT A.* FROM mini_config A WHERE 1=1 ';
        $sqlcount = 'SELECT COUNT(DISTINCT A.`id`) AS tp_count FROM mini_config A WHERE 1=1 ';
        if ($query) {
            $sql .= $query;
            $sqlcount .= $query;
        }
        //order
        $total = $this->query($sqlcount);
        $data['page']['total'] = $total[0]['tp_count'];
        //处理删除最后一条数据的时候没有数据的bug,请求最后一页没有数据的bug
        if(floor(($data['page']['total'] + $row - 1) / $row) < $p && $p != 1){
            $p = $p - 1;
        }
        $sql .= ' ORDER BY A.id desc ';
        $sql .= ' LIMIT '.($p - 1) * $row.','.$row;
        $data['data'] = $this->query($sql);
       
        $data['page']['cur'] = $p;
        $data['page']['row'] = $row;
        // $data['sql'] = $sql;
        return $data;
    }

    /**
     * 编辑加修改.
     */
    public function edit($post)
    {
        if ($post['key'] == '') {
            _apiReturn(0, '配置信息的key不能为空~');
        }
        $post['update_time'] = time();
        //拆分省市区信息,组装config信息
        if ($post['key'] == 'school') {
            $str_arr = explode('/', $post['city-picker']);

            $post['config']['prov'] = $str_arr[0];
            $post['config']['city'] = $str_arr[1];
            $post['config']['area'] = $str_arr[2];
        }

        $post['config'] = json_encode($post['config'], JSON_UNESCAPED_UNICODE);
        $id = $this->where(['key' => $post['key']])->getField('id');
        $data = $this->create($post);
        if ($id) {
            $data['id'] = $id;
            if ($this->save($data)) {
                _apiReturn(1, 'success');
            } else {
                _apiReturn(0, 'error');
            }
        } else {
            if ($this->add($data)) {
                _apiReturn(1, 'success');
            } else {
                _apiReturn(0, 'error');
            }
        }
    }

    /**
     * description  清楚首页缓存.
     */
    public function _clean_home_cache()
    {
        $dir = './Html/Home/';
        if (deldir($dir)) {
            _apiReturn(1, '清除成功');
        } else {
            _apiReturn(0, '清除失败');
        }
    }
}
